﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace PreContractWeb.UserControl
{
    public partial class LeftMenu : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            #region Bind left menu.
            is_first_menu = true;

            Type type = this.Page.Master.GetType();

            string mater_page = type.BaseType.FullName.Substring(type.BaseType.FullName.LastIndexOf(".") + 1);

            string clientPrefix = MenuPanel.ClientID.Replace(MenuPanel.ID, "");

            string clientJs;

            MenuPanel.Controls.Add(NavigationBar(clientPrefix, out clientJs, mater_page));

            Response.Write(clientJs);
            #endregion
        }

        public Panel NavigationBar(string clientPrefix, out string clientJs, string masterPage)
        {

            HtmlTable nav = new HtmlTable();
            nav.ID = "System_Menu";
            nav.Attributes["CurrentItemID"] = "";
            nav.Attributes["CurrentItemStyle"] = "";
            nav.Border = 0;
            nav.CellPadding = 0;
            nav.CellSpacing = 0;
            nav.Style["width"] = "100%";



            BEGDC.PreContract.BLL.IUserRole iuser = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];

            DataSet menuList = iuser.GetPermissionByEmployeeId(((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId);

            int index = 0;
            clientJs = "";

            if (menuList != null)
            {
                StringBuilder js = new StringBuilder();
                js.Append("<script language='javascript' type='text/javascript'> function turnit(subMenuID, menuID) ");
                js.Append("{  if (subMenuID.style.display=='none') {");

                AddSubItem(menuList.Tables[0], "0", nav, ref index, clientPrefix, ref js);

                //report
                js.Append(" if (menuID.id=='ctl00_LeftMenu1_menuitem_12'){ ");
                js.Append(" show('ctl00_LeftMenu1_Div1'); } else { show('Hide'); }");

                js.Append(" subMenuID.style.display=''; ");
                js.Append(" menuID.className='menu_level_1_onfocus'; } ");
                //js.Append("else ");
                //js.Append("{ menuID.className='menu_level_1'; ");
                //js.Append("  subMenuID.style.display='none'; } ");
                js.Append("} </script>");

                clientJs = js.ToString();

                menuList.Dispose();
            }



            Panel panel = new Panel();
            panel.Style["width"] = "100%";
            panel.Style["height"] = "100%";
            //panel.Style["overflow-x"] = "visible";
            //panel.Style["overflow-y"] = "auto";
            panel.Controls.Add(nav);

            return panel;

        }

        private bool is_first_menu;

        private string GetMenuTitle(DataRow row)
        {
            string title = row["MenuTitle_CN"].ToString();

            if (title.Length < 20)
                title += NHibernate.Util.StringHelper.Repeat("&nbsp;", 20 - title.Length);


            return title;
        }

        private void AddSubItem(DataTable menuList, string parentMenuId, HtmlTable parentTable, ref int index, string clientPrefix, ref System.Text.StringBuilder js)
        {


            DataRow[] items = menuList.Select("ParentMenuID = '" + parentMenuId + "'", "MenuSequenceID ASC");

            string parentMenu = string.Empty;
            if (parentMenuId != "0")
            {
                DataRow[] drParentMenu = menuList.Select("MenuID = '" + parentMenuId + "'");
                if (drParentMenu.Length > 0)
                {
                    parentMenu = GetMenuTitle(drParentMenu[0]);
                    parentMenu = parentMenu.Replace("&nbsp;", "");
                }
            }


            for (int i = 0; i < items.Length; i++)
            {
                string itemId = items[i]["MenuID"].ToString();

                if (itemId == "46") //导入Comment的菜单
                {
                    //如果是Admin默认有Comments权限
                    if ((!Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString())))
                    {
                        //如果不是admin, 判断是否有Comments权限
                        if (!((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).CommentAllowed)
                            continue;
                        else
                        {
                            //有comments权限, 但没有Viewer和Editor角色. 则忽略comments权限
                            if (!((Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Editer.ToString())) || (Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Viewer.ToString()))))
                                continue;
                        }
                    }
                }

                //if (itemId == "40") //Delay Report
                //{
                //    if ((!Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString())))
                //        if (!((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).DownloadAllowed)
                //            continue;
                //}

                //if (itemId == "42") //Risk Project
                //{
                //    if ((!Page.User.IsInRole(BEGDC.PreContract.BLL.Role.EnumRole.Admin.ToString())))
                //        if (!((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).DownloadAllowed)
                //            continue;
                //}

                int subItemsCount = menuList.Select("ParentMenuID = '" + itemId + "'", "MenuSequenceID ASC").Length;

                bool hasSub = (subItemsCount > 0);

                int seq = i + 1;

                string menuId = string.Empty;

                string subMenuId = string.Empty;

                HtmlTableRow tr = new HtmlTableRow();

                HtmlTableCell td = new HtmlTableCell();

                td.Attributes["nowrap"] = "nowrap";

                string itemHTML = "";

                BEGDC.PreContract.BLL.Authentication.PCIdentity userid = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);

                string target = "_self";
                string url = string.Empty;



                if (items[i]["ParentMenuID"].ToString() == "0")
                {
                    menuId = "menuitem_" + itemId;
                    td.ID = menuId;

                    if (hasSub)
                    {

                        if (is_first_menu)
                        {
                            td.Attributes["class"] = "menu_level_1_onfocus";
                        }
                        else
                        {
                            td.Attributes["class"] = "menu_level_1";
                        }

                        itemHTML += "<a href='#' class='menu_level_1_title' onclick='turnit(" + clientPrefix + "subMenuGroup_" + seq + ", " + clientPrefix + menuId + ")'>" + GetMenuTitle(items[i]) + "</a>";

                        td.Attributes["title"] = items[i]["MenuTitle"].ToString();
                        td.InnerHtml = itemHTML;
                        tr.Cells.Add(td);
                        parentTable.Rows.Add(tr);
                        js.Append(clientPrefix + "subMenuGroup_" + seq + ".style.display='none';  ");
                        js.Append(clientPrefix + menuId + ".className='menu_level_1';  ");
                    }


                }
                else
                {
                    index++;
                    subMenuId = "sub_menuitem_" + index;
                    td.ID = subMenuId;

                    if (items[i]["Target"].ToString().Trim() == "0")
                    {
                        url = ApplicationUrl();

                        if (items[i]["MenuURL"].ToString().Trim() == string.Empty)
                        {
                            url += "/Notice.aspx";
                        }
                        else
                        {

                            url += items[i]["MenuURL"].ToString().Trim();
                        }
                    }
                    else
                    {
                        target = (string)items[i]["Target"];
                        url = Page.ResolveClientUrl(items[i]["MenuURL"].ToString().Trim());
                    }
                    td.Attributes["class"] = "menu_level_2";
                    td.Attributes["onmousemove"] = "showitem('ctl00_LeftMenu1_" + subMenuId + "');";


                    //if (url.IndexOf("?") > 0)
                    //{
                    //    url += "&PageStyle=" + items[i]["MenuGroup"].ToString();
                    //}
                    //else
                    //{
                    //    url += "?PageStyle=" + items[i]["MenuGroup"].ToString();
                    //}

                    //td.Attributes["onclick"] = "HighlightMenuItem('" + td.ID + "');";

                    // itemHTML += "<a href=\"" + url + "\" class=HomeNavBarLink target=\"" + target + "\" title=\"" + items[i]["MenuTitle_CN"].ToString() + "\">" + items[i]["MenuTitle"].ToString() + "</a>";
                    if (url.ToLower().Contains("task/feedbackprecontract.aspx?isfeedback"))
                    {
                        int count = 0;
                        BEGDC.PreContract.BLL.ISalesFeedback iSalesFeedback = (BEGDC.PreContract.BLL.ISalesFeedback)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_SalesFeedback_Service];

                        if (url.ToLower().Contains("isfeedback=false"))
                        {
                            count = iSalesFeedback.GetNoFeedbackPreContractCount();
                        }

                        if (url.ToLower().Contains("isfeedback=true"))
                        {
                            count = iSalesFeedback.GetFeedbackPreContractCount();
                        }
                        itemHTML += "<a href=\"" + "index.aspx" + "\"  target=\"" + target + "\"   title=\"" + items[i]["MenuTitle"].ToString() + "\"  class=\"menu_level_2\" onclick=\"clickitem('ctl00_LeftMenu1_" + subMenuId + "','" + parentMenu + "','" + url + "');\" >" + items[i]["MenuTitle_CN"].ToString() + "(" + count + ")" + "</a>";
                    }
                    else
                    {
                        itemHTML += "<a href=\"" + url + "\"  target=\"" + target + "\"   title=\"" + items[i]["MenuTitle"].ToString() + "\"  class=\"menu_level_2\" onclick=\"clickitem('ctl00_LeftMenu1_" + subMenuId + "','" + parentMenu + "','" + url + "');\" >" + items[i]["MenuTitle_CN"].ToString() + "</a>";
                    }

                    td.InnerHtml = itemHTML;
                    tr.Cells.Add(td);
                    parentTable.Rows.Add(tr);

                    #region special menu items

                    //else if (itemId == "30")
                    //{
                    //    BEGDC.ECM.BLL.IAdvanceSearch search = (BEGDC.ECM.BLL.IAdvanceSearch)BEGDC.Utility.Castle.AppContainer.Instance["AdvanceSearchService"];
                    //    DataTable dtp = search.GetAdvancedSearchById(((BEGDC.ECM.BLL.Authentication.ECMIdentity)HttpContext.Current.User.Identity).EmployeeId, SearchType.Prepay.Trim());

                    //    for (int j = 0; j < dtp.Rows.Count; j++)
                    //    {
                    //        index++;

                    //        string searchid = dtp.Rows[j]["SearchID"].ToString();

                    //        subMenuId = "sub_menuitem_" + index;

                    //        HtmlTableRow trp = new HtmlTableRow();

                    //        HtmlTableCell tdp = new HtmlTableCell();

                    //        trp.ID = subMenuId;

                    //        target = "_self";

                    //        string titlep = dtp.Rows[j]["SearchName"].ToString();

                    //        string desc1 = dtp.Rows[j]["Description"].ToString();

                    //        if (desc1 == string.Empty)
                    //        {
                    //            desc1 = "Prepay" + titlep;
                    //        }

                    //        url = BaseFunction.ApplicationUrl() + @"/Search/MySearch.aspx?id=" + searchid;

                    //        tdp.Attributes["class"] = "menu_level_2";

                    //        tdp.Style["padding-left"] = "40px";

                    //        //tdp.Attributes["onclick"] = "HighlightMenuItem('" + tdp.ID + "');";

                    //        tdp.Attributes["nowrap"] = "nowrap";

                    //        itemHTML = string.Empty;

                    //        itemHTML += "<a href=\"" + url + "\"  target=\"" + target + "\"   title=\"" + desc1 + "\">" + titlep + "</a>";

                    //        tdp.InnerHtml = itemHTML;

                    //        trp.Cells.Add(tdp);
                    //        parentTable.Rows.Add(trp);

                    //    }
                    //}
                    //else if (itemId == "44")
                    //{
                    //    BEGDC.ECM.BLL.IAdvanceSearch search = (BEGDC.ECM.BLL.IAdvanceSearch)BEGDC.Utility.Castle.AppContainer.Instance["AdvanceSearchService"];

                    //    DataTable dt = search.GetAdvancedSearchById(((BEGDC.ECM.BLL.Authentication.ECMIdentity)HttpContext.Current.User.Identity).EmployeeId, SearchType.AR_Overseas.Trim());

                    //    for (int k = 0; k < dt.Rows.Count; k++)
                    //    {
                    //        index++;

                    //        string searchid = dt.Rows[k]["SearchID"].ToString();

                    //        subMenuId = "sub_menuitem_" + index;

                    //        HtmlTableRow tra = new HtmlTableRow();

                    //        HtmlTableCell tda = new HtmlTableCell();

                    //        tda.ID = subMenuId;

                    //        target = "_self";


                    //        string titlea = dt.Rows[k]["SearchName"].ToString();

                    //        string desc = dt.Rows[k]["Description"].ToString();
                    //        if (desc == string.Empty)
                    //        {
                    //            desc = "AR " + titlea;
                    //        }


                    //        url = BaseFunction.ApplicationUrl() + @"/Search/MySearch.aspx?id=" + searchid;

                    //        tda.Attributes["class"] = "menu_level_2";

                    //        tda.Style["padding-left"] = "40px";

                    //        // tda.Attributes["onclick"] = "HighlightMenuItem('" + tda.ID + "');";


                    //        tda.Attributes["nowrap"] = "nowrap";

                    //        itemHTML = string.Empty;

                    //        itemHTML += "<a href=\"" + url + "\"  target=\"" + target + "\"   title=\"" + desc + "\">" + titlea + "</a>";

                    //        tda.InnerHtml = itemHTML;
                    //        tra.Cells.Add(tda);
                    //        parentTable.Rows.Add(tra);

                    //    }
                    //}
                    //else if (itemId == "45")
                    //{
                    //    BEGDC.ECM.BLL.IAdvanceSearch search = (BEGDC.ECM.BLL.IAdvanceSearch)BEGDC.Utility.Castle.AppContainer.Instance["AdvanceSearchService"];
                    //    DataTable dtp = search.GetAdvancedSearchById(((BEGDC.ECM.BLL.Authentication.ECMIdentity)HttpContext.Current.User.Identity).EmployeeId, SearchType.Prepay_Overseas.Trim());

                    //    for (int j = 0; j < dtp.Rows.Count; j++)
                    //    {
                    //        index++;

                    //        string searchid = dtp.Rows[j]["SearchID"].ToString();

                    //        subMenuId = "sub_menuitem_" + index;

                    //        HtmlTableRow trp = new HtmlTableRow();

                    //        HtmlTableCell tdp = new HtmlTableCell();

                    //        trp.ID = subMenuId;

                    //        target = "_self";

                    //        string titlep = dtp.Rows[j]["SearchName"].ToString();

                    //        string desc1 = dtp.Rows[j]["Description"].ToString();

                    //        if (desc1 == string.Empty)
                    //        {
                    //            desc1 = "Prepay" + titlep;
                    //        }

                    //        url = BaseFunction.ApplicationUrl() + @"/Search/MySearch.aspx?id=" + searchid;

                    //        tdp.Attributes["class"] = "menu_level_2";

                    //        tdp.Style["padding-left"] = "40px";

                    //        //tdp.Attributes["onclick"] = "HighlightMenuItem('" + tdp.ID + "');";

                    //        tdp.Attributes["nowrap"] = "nowrap";

                    //        itemHTML = string.Empty;

                    //        itemHTML += "<a href=\"" + url + "\"  target=\"" + target + "\"   title=\"" + desc1 + "\">" + titlep + "</a>";

                    //        tdp.InnerHtml = itemHTML;

                    //        trp.Cells.Add(tdp);
                    //        parentTable.Rows.Add(trp);

                    //    }
                    //}
                    //else if (itemId == "55")
                    //{
                    //    BEGDC.ECM.BLL.IAdvanceSearch search = (BEGDC.ECM.BLL.IAdvanceSearch)BEGDC.Utility.Castle.AppContainer.Instance["AdvanceSearchService"];
                    //    DataTable dtp = search.GetAdvancedSearchById(((BEGDC.ECM.BLL.Authentication.ECMIdentity)HttpContext.Current.User.Identity).EmployeeId, SearchType.Bill.Trim());

                    //    for (int j = 0; j < dtp.Rows.Count; j++)
                    //    {
                    //        index++;

                    //        string searchid = dtp.Rows[j]["SearchID"].ToString();

                    //        subMenuId = "sub_menuitem_" + index;

                    //        HtmlTableRow trp = new HtmlTableRow();

                    //        HtmlTableCell tdp = new HtmlTableCell();

                    //        trp.ID = subMenuId;

                    //        target = "_self";

                    //        string titlep = dtp.Rows[j]["SearchName"].ToString();

                    //        string desc1 = dtp.Rows[j]["Description"].ToString();

                    //        if (desc1 == string.Empty)
                    //        {
                    //            desc1 = "Prepay" + titlep;
                    //        }

                    //        url = BaseFunction.ApplicationUrl() + @"/Search/MySearch.aspx?id=" + searchid;

                    //        tdp.Attributes["class"] = "menu_level_2";

                    //        tdp.Style["padding-left"] = "40px";

                    //        //tdp.Attributes["onclick"] = "HighlightMenuItem('" + tdp.ID + "');";

                    //        tdp.Attributes["nowrap"] = "nowrap";

                    //        itemHTML = string.Empty;

                    //        itemHTML += "<a href=\"" + url + "\"  target=\"" + target + "\"   title=\"" + desc1 + "\">" + titlep + "</a>";

                    //        tdp.InnerHtml = itemHTML;

                    //        trp.Cells.Add(tdp);
                    //        parentTable.Rows.Add(trp);

                    //    }
                    //}
                    #endregion
                }


                if (hasSub)
                {
                    HtmlTableRow subtr = new HtmlTableRow();
                    //subtr.ID = subMenuId;


                    HtmlTableCell subtd = new HtmlTableCell();
                    subtd.ID = "subMenuGroup_" + seq;
                    if (is_first_menu)
                    {
                        subtd.Attributes["style"] = "display:";
                        subtd.Attributes["class"] = "subMenuGroup";
                        is_first_menu = false;
                    }
                    else
                    {
                        subtd.Attributes["style"] = "display:none";
                        subtd.Attributes["class"] = "subMenuGroup";
                    }



                    subtr.Cells.Add(subtd);
                    parentTable.Rows.Add(subtr);


                    HtmlTable subTable = new HtmlTable();
                    //subTable.Border = 0;
                    //subTable.CellPadding = 0;
                    //subTable.CellSpacing = 0;
                    subTable.Style["width"] = "100%";

                    if (itemId == "12") //Report
                    {
                        HtmlTable htReport = new HtmlTable();
                        htReport.Width = "100%";
                        HtmlTableRow tr1 = new HtmlTableRow();
                        tr1.Height = "10px";

                        //Cell1
                        HtmlTableCell tc1 = new HtmlTableCell();
                        tc1.Style["text-align"] = "center";
                        tc1.Attributes["class"] = "menu";
                        tc1.ID = "TD1";
                        tc1.Height = "10px";
                        tc1.Width = "33%";

                        tc1.InnerHtml = "<a href=\"#\" onclick=\"show('ctl00_LeftMenu1_Div1')\">All</a>";

                        //Cell2

                        HtmlTableCell tc2 = new HtmlTableCell();
                        tc2.Style["text-align"] = "center";
                        tc2.Attributes["class"] = "menu";
                        tc2.ID = "TD2";
                        tc2.Height = "10px";
                        tc2.Width = "33%";

                        tc2.InnerHtml = "<a href=\"#\" onclick=\"show('ctl00_LeftMenu1_Div2')\">ASB</a>";


                        //Cell3

                        HtmlTableCell tc3 = new HtmlTableCell();
                        tc3.Style["text-align"] = "center";
                        tc3.Attributes["class"] = "menu";
                        tc3.ID = "TD3";
                        tc3.Height = "10px";
                        tc3.Width = "33%";

                        tc3.InnerHtml = "<a href=\"#\" onclick=\"show('ctl00_LeftMenu1_Div3')\">Lucent</a>";

                        tr1.Cells.Add(tc1);
                        tr1.Cells.Add(tc2);
                        tr1.Cells.Add(tc3);


                        htReport.Rows.Add(tr1);

                        subtd.Controls.Add(htReport);

                        subTable.Style["Height"] = "193px";
                        HtmlTableRow trReport = new HtmlTableRow();
                        HtmlTableCell tcReport = new HtmlTableCell();
                        tcReport.Height = "193";
                        trReport.Cells.Add(tcReport);
                        subTable.Rows.Add(trReport);
                        subtd.Controls.Add(subTable);

                        AddSubItem(menuList, itemId, Table1, ref index, clientPrefix, ref js);

                        AddSubItem(menuList, itemId, Table2, ref index, clientPrefix, ref js);

                        foreach (HtmlTableRow trRepleace in Table2.Rows)
                        {
                            trRepleace.Cells[0].InnerHtml = trRepleace.Cells[0].InnerHtml.Replace(".aspx", ".aspx?ASBorLucent=0");
                        }

                        AddSubItem(menuList, itemId, Table3, ref index, clientPrefix, ref js);

                        foreach (HtmlTableRow trRepleace in Table3.Rows)
                        {
                            trRepleace.Cells[0].InnerHtml = trRepleace.Cells[0].InnerHtml.Replace(".aspx", ".aspx?ASBorLucent=1");
                        }
                    }
                    else
                    {
                        subtd.Controls.Add(subTable);

                        AddSubItem(menuList, itemId, subTable, ref index, clientPrefix, ref js);
                    }


                }

            }


        }

        private static string ApplicationUrl()
        {
            string rooturl = HttpContext.Current.Request.ApplicationPath;

            if (rooturl == "/")
            {
                return string.Empty;
            }
            else

                return rooturl;


        }
    }
}